<template>
  <div>
    <layout title="配置计划单元" @go="go">
      <resTable :list="resList"></resTable>
    </layout>
    <a-modal v-model="show" :width="600" okText="确定" @ok="ok">
      <a-form-model ref="ruleForm" :model="bulkForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="名称前缀" prop="customCampaignName">
          <a-input v-model="bulkForm.customCampaignName"/>
        </a-form-model-item>
        <a-form-model-item label="类型" prop="ideaTypes">
          <a-checkbox-group v-model="bulkForm.ideaTypes" @change="ontypeCheckChange">
            <a-row style="margin-top:9px;">
              <a-col :span="12">
                <a-checkbox :value="1">自定义</a-checkbox>
              </a-col>
              <a-col :span="12">
                <a-checkbox :value="2">程序化</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-model-item>
        <a-form-model-item label="预算" prop="campaignType">
          <a-radio-group v-model="bulkForm.campaignType" button-style="solid">
            <a-radio-button :value="0">不限</a-radio-button>
            <a-radio-button :value="4">自定义</a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="日预算" prop="budget" v-if="bulkForm.campaignType == 4">
          <a-input-number addon-after="元/天" v-model="bulkForm.budget" :min="50"/> 元/天
        </a-form-model-item>
        <a-form-model-item label="选择商品" prop="jmyPageUrl">
          <a-select v-model="bulkForm.jmyPageUrl" show-search optionFilterProp="name" :filter-option="jmyfilterOption" @search="productSearch">
            <a-spin v-if="fetching" slot="notFoundContent" size="small" />
            <a-select-option :value="item.id" v-for="(item,index) in jmyOptions" :key="index" >
              {{item.name}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="单元模板" prop="sourceTplAdgroupIds">
          <a-select v-model="bulkForm.sourceTplAdgroupIds" mode="multiple" show-search optionFilterProp="adgroupFeedName" :filter-option="jmyfilterOption">
            <div slot="dropdownRender" slot-scope="menu">
              <!-- 自定义select下拉 制作全选功能 -->
              <div style="padding: 4px 8px; cursor: pointer;" @mousedown="e => e.preventDefault()" @click="selectMubanAll" >
                <a-icon type="plus" /> {{selectAllStatus==0?'全选':'取消选择'}}
              </div>
              <a-divider style="margin: 4px 0;" />
              <v-nodes :vnodes="menu" />
            </div>
            <a-select-option :value="item.adgroupFeedId" v-for="(item,index) in tplOptions" :key="index" >
              {{item.adgroupFeedName}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="价格区间">
          <div style="display:flex;align-items:center;">
            <a-input-number v-model="bulkForm.start_price" :min="0" />
            <div style="padding:0 10px;">-</div>
            <a-input-number v-model="bulkForm.end_price" :min="0" />
          </div>
        </a-form-model-item>
        <a-form-model-item label="目标账户" prop="destAccountIds">
          <a-select v-model="bulkForm.destAccountIds" mode="multiple" show-search optionFilterProp="account" :filter-option="jmyfilterOption">
            <a-select-option :value="item.id" v-for="(item,index) in accountList" :key="index" >
              {{item.account}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { getTplAdgroupFeed } from '@/api/xinxiliu/getBaidu'
import { getBdAccountList } from '@/api/xinxiliu/account'
import {getProduct} from '@/api/dianshang/dianshang'
import layout from '../layout'
import resTable from '../resTable'

export default {
  name:'planUnit',
  data() {
    return {
      show:false,
      bulkForm:{
        customCampaignName:'',
        ideaTypes:[1],
        jmyPageUrl:'',
        sourceTplAdgroupIds:[],
        start_price: 0,
        end_price: 0,
        destAccountIds:[],
        campaignType:0,
        budget:50,
      },
      rules:{
        customCampaignName: [{required: true, message: '请输入名称前缀', trigger: 'blur' }],
        ideaTypes: [{required: true, message: '类型不能为空', trigger: 'blur' }],
        jmyPageUrl: [{required: true, message: '请选择基木鱼页面', trigger: 'blur' }],
        sourceTplAdgroupIds: [{required: true, message: '请选择单元模板', trigger: 'blur' }],
        destAccountIds: [{required: true, message: '请选目标账户', trigger: 'blur' }],
        campaignType: [{required: true, message: '请选投放场景', trigger: 'blur' }],
        budget:[{required: true, message: '请填写日预算', trigger: 'blur' }],
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      jmyOptions:[],
      tplOptions:[],
      accountList:[],
      selectAllStatus: 0,

      copy_ideaTypes:[1],

      resList:[],
      productSearchName:'',
      searchTimeout:null,
      fetching:false
    }
  },
  created(){
    this.init()
  },
  methods:{
    init(){
      // this.getJmyPromotionPage()
      this.getTplAdgroupFeed()
      this.getBdAccountList()
      this.getProduct()
    },
    ok(){
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 处理类型
          let ideaTypesText = ''
          for(let item of this.bulkForm.ideaTypes){
            let text = item==1?'自定义':'程序化'
            ideaTypesText += text + '、'
          }
          ideaTypesText = ideaTypesText.substring(0, ideaTypesText.length - 1)
          // 处理单元模板
          let sourceTplAdgroupIdsText = ''
          for(let id of this.bulkForm.sourceTplAdgroupIds){
            let f = this.tplOptions.find(e=>e.adgroupFeedId == id)
            if(f){
              sourceTplAdgroupIdsText += f.adgroupFeedName + '、'
            }
          }
          sourceTplAdgroupIdsText = sourceTplAdgroupIdsText.substring(0, sourceTplAdgroupIdsText.length - 1)
          // 处理目标账户
          let destAccountIdsText = ''
          for(let id of this.bulkForm.destAccountIds){
            let f = this.accountList.find(e=>e.id == id)
            if(f){
              destAccountIdsText += f.account + '、'
            }
          }
          destAccountIdsText = destAccountIdsText.substring(0, destAccountIdsText.length - 1)

          this.resList = [
            {name:'名称前缀', value: this.bulkForm.customCampaignName},
            {name:'类型', value: ideaTypesText},
            {name:'投放场景', value: this.bulkForm.campaignType==1?'普通模式':'放量模式'},
            {name:'基木鱼', value: this.bulkForm.jmyPageUrl},
            {name:'单元模板', value: sourceTplAdgroupIdsText},
            {name:'价格区间', value: this.bulkForm.start_price + ' : ' + this.bulkForm.end_price},
            {name:'目标账户', value: destAccountIdsText},
          ]

          if(this.bulkForm.campaignType == 4){
            this.resList.push({name:'预算', value: this.bulkForm.budget})
          }

          this.show = false
          this.$emit("update:form", this.bulkForm)
        }
      })
    },
    go(){
      this.show = true
    },
    ontypeCheckChange(e){
      if(e.length == 0){
        this.$message.error('必须选择一项')
        this.bulkForm.ideaTypes = JSON.parse(JSON.stringify(this.copy_ideaTypes))
      }
    },
    // getJmyPromotionPage(){
    //   getJmyPromotionPage({}).then((res) => {
    //     if(res.errcode == 0){
    //       this.jmyOptions = res.data.body.data[0].pageList
    //     }
    //   });
    // },
    getTplAdgroupFeed(){
      getTplAdgroupFeed({}).then((res) => {
        if(res.errcode == 0){
          this.tplOptions = res.data
        }
      });
    },
    getBdAccountList(){
      getBdAccountList({}).then((res) => {
        if(res.errcode == 0){
          if(this.bulkForm.destAccountIds.length == 0){
            this.bulkForm.destAccountIds.push(this.$store.state.dianpu.id)
          }
          this.accountList = res.data
        }
        // this.getJmyPromotionPage()
        this.getProduct()
        this.getTplAdgroupFeed()
      })
    },
    getProduct(){
      let params = {
        body:{
          eshopType: 1,
          limit: [0, 100],
          isDesc: true,
        }
      }
      this.fetching = true
      // 添加搜索筛选
      if(this.productSearchName != ''){
        params.body.filters = [
          {
            field: "name|id",
            op: "like",
            values: [this.productSearchName]
          }
        ]
      }
      getProduct(params).then((res) => {
        this.fetching = false
        if(res.errcode == 0){
          this.jmyOptions = res.data.body.data
        }
      }).catch(() => {
        this.fetching = false
      });
    },
    jmyfilterOption(input, option){
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    productSearch(val){
      this.productSearchName = val
      this.searchTimeout && clearTimeout(this.searchTimeout)
      this.searchTimeout = setTimeout(() => {
        if(val != ""){
          this.getProduct()
        }
      }, 800);
    },
    selectMubanAll(){
      // 单元模板全选
      let arr = []
      if(this.selectAllStatus == 0){
        this.tplOptions.forEach(e => {
          arr.push(e.adgroupFeedId)
        });
        this.selectAllStatus = 1
      }else{
        this.selectAllStatus = 0
      }
      this.bulkForm.sourceTplAdgroupIds = arr
    },
  },
  components:{layout, resTable, VNodes: {
    functional: true,
    render: (h, ctx) => ctx.props.vnodes,
  },},
  watch:{
    'bulkForm.ideaTypes'(e){
      this.copy_ideaTypes = JSON.parse(JSON.stringify(e))
    }
  },
}
</script>

<style lang="less" scoped>
/deep/ .ant-select-selection--multiple{
  max-height: 140px;
  overflow-y: auto;
}
</style>